import json
from time import thread_time
import requests
from typing import Literal
from PyQt5.QtCore import QObject, QThread, pyqtSignal, QRunnable, QThreadPool
from PyQt5.QtWidgets import QWidget

from app.common.setting import RESOURCES
from app.components.resourceCard import ResourceCard


""" 
CategoryId
11 : mod
12 : map
13 : skin
14 : pack

"""

class ThreadStartsResourceLoading(QRunnable):
    def __init__(self, threadList):
        super().__init__()
        self.threadList = threadList
        self.setAutoDelete(True)
    
    def run(self):
        for thread in self.threadList:
            thread.start()

ThreadLoadPool = QThreadPool()
        

class LoadResourceThread(QThread):
    pageNumber = pyqtSignal(int)
    pageCardInformation = pyqtSignal(dict)

    def __init__(
        self,
        categoryId: int = 11,
        keyword: str = "",
        mode: Literal["getPage", "getResource"] = "getPage",
        page: int = 1,
    ) -> None:
        """
        __init__ 线程初始

        提供资源加载模块
        11 -> Mod
        12 -> Map
        13 -> Skin
        14 -> Pack

        Args:
            categoryId (int, optional): 分类代码. Defaults to 11.
            keyword (str, optional): 关键字搜索,默认为不搜索. Defaults to "".
            mode (Literal[&quot;getPage&quot;, &quot;getResource&quot;], optional): 调取模式;getPage获取当前资源分页;getResource获取当前页的资源. Defaults to "getPage".
            page (int, optional): 获取页数,当模式为getPage时可不填. Defaults to 1.
        """

        super().__init__()
        self.categoryId = categoryId
        self.keyword = keyword
        self.mode: Literal["getPage", "getResource"] = mode
        self.page = page
        self.size = 20

        # 判断调取模式
        if self.mode == "getPage":
            self.jsons = {
                "page": 1,
                "size": 20,
                "categoryId": self.categoryId,
                "keyword": self.keyword,
                "queryOrderByEnum": "HOT",
            }
        elif self.mode == "getResource":
            self.jsons = {
                "page": self.page,
                "size": 20,
                "categoryId": self.categoryId,
                "keyword": self.keyword,
                "queryOrderByEnum": "HOT",
            }

    def run(self):
        result = None
        try:
            r = requests.get(RESOURCES, params=self.jsons)
        except Exception as e:
            print(f"在请求分类为{self.categoryId}的资源时出错 ->\n{e}")
        else:
            result = json.loads(r.text)
            if result["code"] != 200:
                result = None

        if result:
            if self.mode == "getPage":
                self.pageNumber.emit(result["data"]["page"])
            elif self.mode == "getResource":
                resourcesList = result["data"]["resources"]
                for resource in resourcesList:
                    resource["currentPage"] = self.page
                    self.pageCardInformation.emit(resource)

        self.quit()
